package com.foryou.system.common.controller;

import com.foryou.system.common.exception.RollbackException;
import com.foryou.system.common.utils.FileUtil;
import com.foryou.system.common.utils.R;
import com.foryou.system.common.utils.ShiroUtils;
import com.foryou.system.modules.sys.service.SysUserService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author: Mr.Li
 * @Date: 2018-08-26 22:10
 * @Description: 公共上传地址
 **/
@RestController
@RequestMapping("/common/")
public class CommonController {

    @Value("${web.upload-path}")
    private String path;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("upload")
    public R uploadFiles(@RequestParam MultipartFile[] uploadFile) throws Exception {
        for (MultipartFile file : uploadFile) {
            if (file.isEmpty()) {
                throw new RollbackException("文件未上传");
            } else {
                try {
                    String saveName = FileUtil.RenameToUUID(file.getOriginalFilename());
                    FileUtil.uploadFile(file.getBytes(), path, saveName);
                    String uploadURL = "/upload/" + saveName;
                    return R.ok().put("uploadURL", uploadURL);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return R.error();
    }

    @Autowired
    private Producer producer;

    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("checkUserName")
    public R checkUserName(String username) {
        boolean result = sysUserService.queryUserByUsername(username)==null;
        return R.ok().put("valid", result);
    }

}
